package com.winer.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.winer.dto.UserDTO;
import com.winer.dto.Result;
import com.winer.entity.User;
import com.winer.mapper.UserMapper;
import com.winer.service.LoginService;
import com.winer.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.winer.constant.JwtConstants.*;
import static com.winer.constant.RedisConstants.*;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

   @Autowired
   private UserMapper userMapper;


   @Autowired
   private StringRedisTemplate stringRedisTemplate;

    /**登录效验
     *
     * @param userDTO
     * @return
     */
    @Override
    public Result userLogin(UserDTO userDTO) {


        String phone = userDTO.getPhone();
        String role = userDTO.getRole();
        //效验验证码
        String code = userDTO.getCode();
        Object cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+":"+ role + phone );
        if (cacheCode == null || !cacheCode.toString().equals(code)) {
            //不一致，报错
            return Result.fail("验证码错误");
        }
        if (role.equals("expert") ) {
            User user = userMapper.queryByPhoneAndRole(phone, role);
            if (user == null){
                return Result.fail("请联系管理员");
            }
            return Result.ok();
        }
        User user = userMapper.queryByPhoneAndRole(phone, role);
        String userID = UUID.randomUUID().toString().replace("-", "");
        if (user == null) {

            LocalDateTime now = LocalDateTime.now();
            userMapper.saveUser(phone,role,userID,now);
        }

        //生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        log.info("token:{}",userID);
        //playLoad负载uuid
        claims.put(TOKEN_PLAYLOAD,userID);
        //adminSecretKey签名,adminTtl过期时间,
        String token = JwtUtil.createJWT(SECRET_KEY, TOKEN_TTL, claims);
        //存入redis,userkey
        String key = USER_KEY + userID;
        stringRedisTemplate.opsForHash().put(key,USER_PHONE_KEY,phone);
        stringRedisTemplate.opsForHash().put(key,USER_ROLE_KEY,role);

        log.info("token:{}",token);

        log.info("token:{}",phone);
        log.info("token:{}",role);
        return Result.ok(token);
    }

    /**生成验证码
     *
     * @param userDTO
     * @return
     */
    @Override
    public Result sendCode(UserDTO userDTO) {

        String phone = userDTO.getPhone();
        String role = userDTO.getRole();
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+":"+role + phone , code,LOGIN_CODE_TTL , TimeUnit.MINUTES);
        //发送验证码
        log.info("发送短信验证码成功，验证码是:{}",code);

        return Result.ok(code);
    }


}
